package com.tourism.core.cn.config;
/*********************************************************************
 Copyright(c) 2025 All Rights Reserved .
 Author : liliang
 CreatedOn : 2025/1/2 23:43
 Email : 2061996582@qq.com
 Describe : Redis配置类
 UseCase :
 Version : 2025|V1.0.0.0
 **********************************************************************/

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author new
 * @date 2025/1/2 23:43
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(@Autowired RedisConnectionFactory connectionFactory) {
        if (connectionFactory == null) {
            throw new IllegalArgumentException("RedisConnectionFactory is required");
        }

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 使用 StringRedisSerializer 来序列化和反序列化 redis 的 key
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        // 使用 GenericJackson2JsonRedisSerializer 来序列化和反序列化 redis 的 value
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);

        // 设置支持事务
        template.setEnableTransactionSupport(true);
        template.afterPropertiesSet();

        return template;
    }
}
